package org.javacore.net;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created by Fan on 2017/3/5.
 */

/**
 * 使用telnet localhost 8189 连接到此服务，输入Bye即断开连接同时服务器程序终止运行，输入其他则打印该信息
 */
public class EchoServer {
    public static void main(String[] args) throws IOException {
        try (ServerSocket s = new ServerSocket(8189)){  //绑定端口
            try (Socket incoming= s.accept()){  //等待连接（监听）
                InputStream inputStream = incoming.getInputStream();
                OutputStream outputStream = incoming.getOutputStream();
                try (Scanner in = new Scanner(inputStream)){
                    PrintWriter out = new PrintWriter(outputStream,true);
                    out.println("Hello! Enter Bye to exit.");
                    boolean done = false;
                    while (!done && in.hasNextLine()){
                        String line = in.nextLine();
                        out.println("Echo: "+line);
                        if (line.trim().equals("Bye")){
                            done = true;
                        }
                    }
                }
            }
        }
    }
}
